package com.qingke.memo.command.system;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import com.qingke.memo.command.SystemCommand;
import com.qingke.memo.pojo.Days;
import com.qingke.memo.pojo.Memo;
import com.qingke.memo.unit.MConsole;

public class SelectMemoByCreateTime extends SystemCommand {

	@Override
	public void execute() {
		String startStr=MConsole.promptNotEmpty("start date:");
		if(!matcher(startStr)){
			MConsole.println("err input");
			return ;
		}
		
		String endStr=MConsole.promptNotEmpty("end date:");
		if(!matcher(endStr)){
			MConsole.println("err input");
			return ;
		}
		
		Date start=toDate(startStr);
		Date end=toDate(endStr);
		if(start.after(end)){
			MConsole.println("err input");
			MConsole.println("start date can not after end date.");
			return;
		}
		
		Days days=new Days();
		days.setStartDate(start);
		days.setEndDate(new Date(end.getTime()+24*60*60*1000));
		
		List<Memo> list=dao.selectMemosByCreateTime(days);
		if(list.size()==0){
			MConsole.println("no result");
			return ;
		}
		
		MConsole.println("-------memos-------");
		Collections.sort(list, new Comparator<Memo>(){
			@Override
			public int compare(Memo o1, Memo o2) {
				return -o1.getCreateTime().compareTo(o2.getCreateTime());
			}
		});
		for(Memo m:list){
			MConsole.println(m.toSimpleString());
		}
		MConsole.println();
	}

	@SuppressWarnings("deprecation")
	private boolean matcher(String str){
		Pattern datePattern = Pattern.compile("[0-9]{4}[^0-9][0-9]{1,2}[^0-9][0-9]{1,2}");
		if(!datePattern.matcher(str).find())
			return false;
		String[] ymd=str.split("[^0-9]");
		int year=Integer.parseInt(ymd[0]);
		if(year<1900)
			return false;
		int month=Integer.parseInt(ymd[1]);
		if(month>12)
			return false;
		int day=Integer.parseInt(ymd[2]);
		if(day>31)
			return false;
		try{
			new Date(year,month,day);
		}catch(Exception e){
			return false;
		}
		
		return true;
	}
	
	@SuppressWarnings("deprecation")
	public Date toDate(String str){
		String[] ymd=str.split("[^0-9]");
		int year=Integer.parseInt(ymd[0])-1900;
		int month=Integer.parseInt(ymd[1])-1;
		int day=Integer.parseInt(ymd[2]);
		return new Date(year,month,day);
	}
	
//	public static void main(String[] args){
//		SelectMemoByCreateTime s=new SelectMemoByCreateTime();
//		System.out.println(s.matcher("0000-0-0"));
//		System.out.println(s.toDate("2005-1-2"));
//		
//	}
}
